from flask import Blueprint, render_template, redirect, url_for, flash, request
from app.utils.decorators import admin_required
from app.models.user import User
from app import db

bp = Blueprint('admin', __name__, url_prefix='/admin')

@bp.route('/users')
@admin_required
def users():
    # 获取查询参数
    page = request.args.get('page', 1, type=int)
    per_page = 10  # 每页显示10条记录
    search = request.args.get('search', '')
    user_type = request.args.get('user_type', '')

    # 构建查询
    query = User.query
    
    # 添加搜索条件
    if search:
        query = query.filter(User.username.like(f'%{search}%'))
    
    # 添加用户类型过滤
    if user_type:
        query = query.filter(User.user_type == user_type)
    
    # 执行分页查询
    pagination = query.order_by(User.id.desc()).paginate(
        page=page, per_page=per_page, error_out=False)
    
    return render_template('admin/users.html', 
                         pagination=pagination,
                         search=search,
                         user_type=user_type,
                         user_types=User.USER_TYPES)

@bp.route('/user/<int:id>/delete', methods=['POST'])
@admin_required
def delete_user(id):
    user = User.query.get_or_404(id)
    if user.user_type == 'admin':
        flash('不能删除管理员账号', 'danger')
    else:
        db.session.delete(user)
        db.session.commit()
        flash('用户已删除', 'success')
    return redirect(url_for('admin.users')) 